package com.sjzs.web.interceptor;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.annotations.AnnotationWorkflowInterceptor;

public class PathToRootInterceptor extends AnnotationWorkflowInterceptor {
	private static final long serialVersionUID = 2622248016231160818L;
	private transient Logger logger = LoggerFactory.getLogger(getClass());
	private static final String PATH_SEPARATOR = "/";
	private static final String BACK_TRACK_COMMAND = "..";

	public String intercept(ActionInvocation invocation) throws Exception {
		ActionContext context = invocation.getInvocationContext();
		HttpServletRequest request = ServletActionContext.getRequest();
		logger.debug("request:" + request);
		if (request != null) {
			String servletPath = request.getServletPath();
			int numberOfSubDirectories = servletPath.split(PATH_SEPARATOR).length - 2;

			String pathToRoot = numberOfSubDirectories > 0 ? getPathToRoot(numberOfSubDirectories) : "";
			context.getValueStack().setValue("pathToRoot", pathToRoot);
			logger.debug("pathToRoot:" + pathToRoot);
		}
		return invocation.invoke();
	}

	private String getPathToRoot(int numberOfSubDirectories) {
		StringBuilder pathToRoot = new StringBuilder("..");
		for (int i = 0; i < numberOfSubDirectories - 1; i++) {
			pathToRoot.append(PATH_SEPARATOR + BACK_TRACK_COMMAND);
		}
		return pathToRoot.toString();
	}
}
